﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using DMS.Business.Modules.ArchivesManagement;
using DMS.Data;
using DMS.Business.Modules.SystemManagement;
using DMS.Business.Utility;
using DMS.Business.Modules.Organization;

namespace DMS.Web.Modules.ArchivesManagement
{
    public partial class BaseInfoList : System.Web.UI.Page
    {
        #region 属性

        private AuthenticationUser _loginUser;

        private AuthenticationUser LoginUser
        {
            get
            {
                if (_loginUser == null)
                {
                    _loginUser = SystemContext.Current.LoginAuthUser;
                }
                return _loginUser;
            }
        }

        /// <summary>
        /// normal/urge/overtime/warning/complain/unPrint/unArrive/unBack
        /// </summary>
        public string FormType
        {
            get { return Request["type"]; }
        }

        public string DefaultDisplayStyle
        {
            get { return FormType == "GR" ? "none" : ""; }
        }

        public string GRDisplayStyle
        {
            get { return FormType != "GR" ? "none" : ""; }
        }

        private IQueryable<AM_BaseInfo> BaseInfos { get; set; }

        public bool IsDeveliryMan
        {
            get { return UserHelper.IsUserInRole(LoginUser, "配送管理员;系统管理员"); }
        }

        /// <summary>
        /// 预警
        /// </summary>
        private int DelayWarning
        {
            get { return int.Parse(ConfigHelper.GetSysConfigByID("DelayWarning").Value); }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitControls();
                Search();
            }
            //CurrentPage.Checked = false;
        }

        private void InitControls()
        {
            switch (FormType)
            {
                case "DW":
                    this.currentListName.Text = "单位基本信息";
                    break;
                case "GTH":
                    this.currentListName.Text = "个体户基本信息";
                    break;
                case "GR":
                    this.currentListName.Text = "个人基本信息";
                    break;
            }

            //个人
            if (FormType == "GR")
            {
                baseInfoList.Columns[4].Visible = false;
                baseInfoList.Columns[5].Visible = false;

                baseInfoList.Columns[6].Visible = true;
                baseInfoList.Columns[7].Visible = true;
                baseInfoList.Columns[8].Visible = true;

                baseInfoList.Columns[12].Visible = false;
            }

            if (!SystemContext.Current.LoginUser.IsInRole("档案管理员;系统管理员;"))
            {
                this.uploadBtn.Visible = false;
                this.addBtn.Visible = false;
                this.btnClear.Visible = false;
            }
        }

        public string CondtionString
        {
            get { return this.Condition.Value+";"+this.currentListName.Text; }
        }

        private void Search()
        {
            int total;
            string condition = GetCondition();
            //缓存到页面隐藏字段
            this.Condition.Value = condition;

            if (this.PageSize.Text == "")
                this.PageSize.Text = "15";
            pager.PageSize = int.Parse(this.PageSize.Text);
            List<AM_BaseInfo> list = BaseInfoService.GetBaseInfos(SystemContext.Current.LoginUser, condition,
                                                                  pager.CurrentPageIndex, pager.PageSize, out total);

            foreach (GridViewRow gr in baseInfoList.Rows)
            {
                HtmlInputCheckBox cb = (HtmlInputCheckBox) gr.Cells[0].FindControl("chkItem");
                string id = cb.Attributes["value"].Split(',')[0];
                if (ViewState[id] != null)
                {
                    ViewState.Remove(id);
                }
            }

            // 获取GridView排序数据列及排序方向
            string sortExpression = this.baseInfoList.Attributes["SortExpression"];
            string sortDirection = this.baseInfoList.Attributes["SortDirection"];

            IQueryable<AM_BaseInfo> queryableList;
            // 根据GridView排序数据列及排序方向设置显示的默认数据视图
            if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
            {
                //调用排序方法对当前页数据进行排序
                queryableList = (list.AsQueryable()).OrderUsingSortExpression(sortExpression + " " + sortDirection);
            }
            else
            {
                queryableList = list.AsQueryable();
            }

            BaseInfos = queryableList;

            // GridView绑定并显示数据
            this.baseInfoList.DataSource = queryableList;
            this.baseInfoList.DataBind();

            pager.RecordCount = total;
        }

        protected void baseInfoList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                AM_BaseInfo baseInfo = BaseInfos.ToList()[e.Row.RowIndex];

                //转化保险类型
                Label InsuranceType = e.Row.FindControl("InsuranceType") as Label;
                string typeString = "";
                if (bool.Parse(baseInfo.Yanglao.ToString()))
                    typeString += "养老、";
                if (bool.Parse(baseInfo.Gongshang.ToString()))
                    typeString += "工伤、";
                if (bool.Parse(baseInfo.Shiye.ToString()))
                    typeString += "失业、";
                if (bool.Parse(baseInfo.Yiliao.ToString()))
                    typeString += "医疗、";
                if (bool.Parse(baseInfo.Shengyu.ToString()))
                    typeString += "生育、";
                if (!string.IsNullOrEmpty(typeString))
                {
                    typeString = typeString.Substring(0, typeString.Length - 1);
                }
                InsuranceType.Text = typeString;
            }
        }
        
        protected void DealCommand(object sender, GridViewCommandEventArgs e)
        {
            string commandName = e.CommandName;
            var id = e.CommandArgument as string;
            if (commandName.Equals("DeleteBaseInfo"))
            {
                BaseInfoService.DeleteBaseInfo(id);
            }
            Search();
        }

        //列表的排序事件
        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            // 从事件参数获取排序数据列
            string sortExpression = e.SortExpression.ToString();
            // 假定为排序方向为“顺序”
            string sortDirection = "ASC";
            // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
            if (sortExpression == baseInfoList.Attributes["SortExpression"])
            {
                //获得下一次的排序状态
                sortDirection = (baseInfoList.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");
            }
            // 重新设定GridView排序数据列及排序方向
            baseInfoList.Attributes["SortExpression"] = sortExpression;
            baseInfoList.Attributes["SortDirection"] = sortDirection;
            
            Search();
        }


        protected string GetCondition()
        {
            string condition = "";

            condition += string.Format(" and it.Type='{0}'", FormType);

            if (txtBoxCode.Text != "")
            {
                condition += string.Format(" and it.BoxCode like '%{0}%'", txtBoxCode.Text.Trim());
            }
            if (txtInsuranceCode.Text != "")
            {
                condition += string.Format(" and it.InsuranceCode like '%{0}%'", txtInsuranceCode.Text.Trim());
            }
            if (txtTaxCode.Text != "")
            {
                condition += string.Format(" and it.TaxCode like '%{0}%'", txtTaxCode.Text.Trim());
            }
            if (txtBoxPosition.Text != "")
            {
                condition += string.Format(" and it.BoxPosition like '%{0}%'", txtBoxPosition.Text.Trim());
            }
            if (txtUnitName.Text != "")
            {
                condition += string.Format(" and it.UnitName like '%{0}%'", txtUnitName.Text.Trim());
            }
            if (txtPayerName.Text != "")
            {
                condition += string.Format(" and it.PayerName like '%{0}%'", txtPayerName.Text.Trim());
            }
            if (txtIdentityCardNo.Text != "")
            {
                condition += string.Format(" and it.IdentityCardNo like '%{0}%'", txtIdentityCardNo.Text.Trim());
            }
            if (txtBeginRegistDate.Text != "")
            {
                condition += string.Format(" and it.RegistDate >= cast('{0}' as System.DateTime)", DateTime.Parse(txtBeginRegistDate.Text));
            }
            if (txtEndRegistDate.Text != "")
            {
                condition += string.Format(" and it.RegistDate < cast('{0}' as System.DateTime)", DateTime.Parse(txtEndRegistDate.Text).AddDays(1));
            }
            
            if (txtPayUnitType.Text != "")
            {
                condition += string.Format(" and it.PayUnitType like '%{0}%'", txtPayUnitType.Text.Trim());
            }
            if (txtAdmin.Text != "")
            {
                condition += string.Format(" and it.Admin like '%{0}%'", txtAdmin.Text.Trim());
            }
            if (cbYanglao.Checked)
            {
                condition += " and it.Yanglao = true ";
            }
            if (cbGongshang.Checked)
            {
                condition += " and it.Gongshang = true ";
            }
            if (cbShiye.Checked)
            {
                condition += " and it.Shiye = true ";
            }
            if (cbYiliao.Checked)
            {
                condition += " and it.Yiliao = true ";
            }
            if (cbShengyu.Checked)
            {
                condition += " and it.Shengyu = true ";
            }

            return condition;
        }

        protected  void cleartemp_Click(object sender, EventArgs e)
        {
            BaseInfoTempService.RemoveAllTempRecord();
            ClientHelper.Instance.Alert("清理临时空间成功！");
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Search();
        }

        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void pager_PageChanged(object sender, EventArgs e)
        {
            Search();
        }

        protected void ExportClick(object sender, EventArgs e)
        {
            string condition = GetCondition();

            Dictionary<string, DataTable[]> forms = new Dictionary<string, DataTable[]>();
            List<DataTable> tables = BaseInfoService.GetBaseInfoTable(SystemContext.Current.LoginUser, condition,
                                                                      FormType);
            
            if(tables==null)
            {
                ClientHelper.Instance.Alert("导出记录数超过Excel的最大行数（65535），请先筛选数据，分多次导出，谢谢。");
                return;
            }

            forms.Add(this.currentListName.Text, tables.ToArray());
            try
            {
                ClientHelper.Instance.ExportToExcel(forms, this.currentListName.Text);
            }catch(Exception ex)
            {
                LogHelper.LogException(ex);
            }
            
        }

//        protected void PrintClick(object sender, EventArgs e)
//        {
//            string id = null;
//            HtmlInputCheckBox cb = null;
//            StringBuilder idBuilder = new StringBuilder(); 
//            foreach (GridViewRow gr in gvList.Rows)//改成只打一页，按页面顺序打印出来
//            {
//                cb = (HtmlInputCheckBox)gr.Cells[0].FindControl("chkItem");
//                id = cb.Attributes["value"].Split(',')[0];
//                //if (cb.Checked)
//                //{
//                //    ViewState[id] = id;
//                //}
//                //else
//                //{
//                //    if (ViewState[id] != null)
//                //    {
//                //        ViewState.Remove(id);
//                //    }
//                //}
//                if (cb.Checked)
//                    idBuilder.Append(id).Append("~");
//            }
            
//            //foreach (string orderId in ViewState.Keys)
//            //{
//            //    idBuilder.Append(orderId).Append("~");
//            //}

//            if(idBuilder.Length > 0)
//            {
//                ClientHelper.Instance.RenderScript(Page, "", String.Format("printOrder('{0}')", idBuilder.ToString()));
//            }
//        }

//        protected void ExportClick(object sender, EventArgs e)
//        {
//            string condition = GetConditionForExport();

//            Dictionary<string, DataTable[]> forms = new Dictionary<string, DataTable[]>();
//            List<DataTable> tables = OrderFormService.GetOrdersTable(SystemContext.Current.LoginAuthUser, condition,
//                                                                     FormType);
//            if(tables==null)
//            {
//                ClientHelper.Instance.Alert("导出记录数超过Excel的最大行数（65535），请先筛选数据，分多次导出，谢谢。");
//                return;
//            }

//            forms.Add(Convert.ToString("配送单明细"), tables.ToArray());

//            ClientHelper.Instance.ExportToExcel(forms, "配送单明细");
//        }

//        protected string GetConditionForExport()
//        {
//            string condition = "";

//            string inputOrderNo = txtOrderNo.Text.Replace(",", "").Replace("'", "").Trim();
//            using (StringReader sr = new StringReader(inputOrderNo))
//            {
//                StringBuilder inString = new StringBuilder();
//                string strLineData;
//                int i = 0;
//                while ((strLineData = sr.ReadLine())!=null)
//                {
//                    if (strLineData.Trim() != "")
//                    {
//                        strLineData = strLineData.Trim();
//                        inString.Append("'" + strLineData + "',");
//                        i++;
//                    }
//                }
//                if (i > 1)
//                {
//                    condition += " and it.OrderNo in (" + inString.ToString().Substring(0, inString.Length - 1) + ")";
//                }
//                else
//                {
//                    if (txtOrderNo.Text != "")
//                    {
//                        condition += string.Format(" and it.OrderNo like '%{0}%'", txtOrderNo.Text.Trim());
//                    }
//                }
//            }

//            string inputSourceNo = txtSourceNo.Text.Replace(",", "").Replace("'", "").Trim();
//            using (StringReader sr = new StringReader(inputSourceNo))
//            {
//                StringBuilder inString = new StringBuilder();
//                string strLineData;
//                int i = 0;
//                while ((strLineData = sr.ReadLine())!=null)
//                {
//                    if (strLineData.Trim() != "")
//                    {
//                        strLineData = strLineData.Trim();
//                        inString.Append("'" + strLineData + "',");
//                        i++;
//                    }
//                }
//                if (i > 1)
//                {
//                    condition += " and it.SourceNo in (" + inString.ToString().Substring(0, inString.Length - 1) + ")";
//                }
//                else
//                {
//                    if (txtSourceNo.Text != "")
//                    {
//                        condition += string.Format(" and it.SourceNo like '%{0}%'", txtSourceNo.Text.Trim());
//                    }
//                }
//            }

//            string inputCarryNo = txtCarryNo.Text.Replace(",", "").Replace("'", "").Trim();
//            using (StringReader sr = new StringReader(inputCarryNo))
//            {
//                StringBuilder inString = new StringBuilder();
//                string strLineData;
//                int i = 0;
//                while ((strLineData = sr.ReadLine())!=null)
//                {
//                    if (strLineData.Trim() != "")
//                    {
//                        strLineData = strLineData.Trim();
//                        inString.Append("'" + strLineData + "',");
//                        i++;
//                    }
//                }
//                if (i > 1)
//                {
//                    condition += " and it.CarryNo in (" + inString.ToString().Substring(0, inString.Length - 1) + ")";
//                }
//                else
//                {
//                    if (txtCarryNo.Text != "")
//                    {
//                        condition += string.Format(" and it.CarryNo like '%{0}%'", txtCarryNo.Text.Trim());
//                    }
//                }
//            }
//            if (txtApplier.Text != "")
//            {
//                condition += string.Format(" and it.Applier like '%{0}%'", txtApplier.Text);
//            }
//            if (txtApplierBigDept.Text != "")
//            {
//                condition += string.Format(" and it.ApplierBigDept like '%{0}%'", txtApplierBigDept.Text);
//            }

//            if (this.txtBeginInitialTime.Text.Trim() != "" && this.txtEndInitialTime.Text.Trim() != "")
//            {
//                DateTime dt = DateTime.Parse(this.txtEndInitialTime.Text.Trim());
//                dt = dt.AddDays(1);
//                condition += string.Format(" AND it.InitialTime>='{0}' AND it.InitialTime<'{1}'",
//                                           this.txtBeginInitialTime.Text.Trim(), dt.ToString());
//            }
//            if (this.txtBeginInitialTime.Text.Trim() != "")
//            {
//                condition += string.Format(" AND it.InitialTime>='{0}'", this.txtBeginInitialTime.Text.Trim());
//            }
//            if (this.txtEndInitialTime.Text.Trim() != "")
//            {
//                DateTime dt = DateTime.Parse(this.txtEndInitialTime.Text.Trim());
//                dt = dt.AddDays(1);
//                condition += string.Format(" AND it.InitialTime<'{0}'", dt.ToString());
//            }
//            if (txtReceiver.Text != "")
//            {
//                condition += string.Format(" and it.Receiver like '%{0}%'", txtReceiver.Text);
//            }
//            if (txtSendAddress.Text != "")
//            {
//                condition += string.Format(" and it.SendAddress like '%{0}%'", txtSendAddress.Text);
//            }
//            if (txtReceiveAddress.Text != "")
//            {
//                condition += string.Format(" and it.ReceiveAddress like '%{0}%'", txtReceiveAddress.Text);
//            }
//            if (ddlProjectType.SelectedIndex != 0)
//            {
//                condition += string.Format(" and it.ProjectTypeName = '{0}'", ddlProjectType.SelectedItem.Text);
//            }
//            if (!string.IsNullOrEmpty(ProjectChildTypeID.SelectedValue))
//            {
//                condition += string.Format(" and it.ProjectChildTypeID = '{0}'", ProjectChildTypeID.SelectedValue);
//            }
//            if (ddlSupplier.SelectedIndex != 0)
//            {
//                condition += string.Format(" and it.SupplierID = '{0}'", ddlSupplier.SelectedValue);
//            }
//            if (ddlStatus.SelectedIndex != 0)
//            {
//                condition += string.Format(" and it.Status = '{0}'", ddlStatus.SelectedValue);
//            }
//            //超时
//            if (FormType == "delay")
//            {
//                //包括送达超时和回单超时
//                //送达超时条件：1）送达超时没有及时回复；2）当前时间距离下单时间已经超过一定天数；3）送达时间为空空或者送达时间距离下单时间超过一定天数
//                //回单超时条件：1）需要回单；2）回单超时没有及时回复；3）送达时间不为空；4）当前时间距离送达时间超过一定天数；5）回单时间为空或者回单时间距离送达时间超过一定天数
//                condition +=
//                    string.Format(
//                        @"
//                         and it.IsReplyIntime_DelayArrive is null 
//                         and 
//                        (
//                        (DATEDIFF(day,it.InitialTime,GETDATE())>{0} 
//                        and (it.ArriveTime is null or DATEDIFF(day,it.InitialTime,it.ArriveTime)>{0}))
//                        or
//                        (it.IsBack = 1 and it.ArriveTime is not null
//                        and DATEDIFF(day,it.ArriveTime,GETDATE())>{0} 
//                        and (it.BackTime is null or DATEDIFF(day,it.ArriveTime,it.BackTime)>{0}))
//                        )",
//                        NormalDelay);
//            }

//            //预警
//            if (FormType == "warning")
//            {
//                //包括送达预警和回单预警
//                //送达预警条件：1）送达时间为空；2）当前时间与下单时间间隔超过一定天数但还没超时
//                //回单预警条件：1）需要回单；2）回单时间为空；3）当前时间与送达时间间隔超过一定天数但还没超时
//                condition +=
//                    string.Format(
//                        @" and 
//                            (
//                            (it.ArriveTime is null and DATEDIFF(day,it.InitialTime,GETDATE())>{0} and DATEDIFF(day,it.InitialTime,GETDATE())<={1})
//                            or
//                            (it.IsBack = 1 and it.BackTime is null and DATEDIFF(day,it.ArriveTime,GETDATE())>{0} and DATEDIFF(day,it.ArriveTime,GETDATE())<={1})
//                            )",
//                        DelayWarning, NormalDelay);
//            }

//            //催办
//            if (FormType == "urge")
//            {
//                condition += " and it.UrgeTime is not null";
//            }

//            //投诉
//            if (FormType == "complain")
//            {
//                condition += " and it.ComplainTime is not null";
//            }

//            //未打印
//            if (FormType == "unPrint")
//            {
//                condition += " and it.PrintTime is null";
//            }

//            //未送达
//            if (FormType == "unArrive")
//            {
//                condition += " and it.ArriveTime is null";
//            }

//            //未回单
//            if (FormType == "unBack")
//            {
//                condition += " and it.IsBack = 1 and it.ArriveTime is not null and it.BackTime is null";
//            }

//            //收件区域
//            if (ddlArea.SelectedItem.Text == "市内")
//            {
//                condition += " and it.ReceiveCity='440100' and it.ReceiveArea not in('440183','440184','440113','440114','440107')";
//            }
//            if (ddlArea.SelectedItem.Text == "市郊")
//            {
//                condition += " and it.ReceiveArea in ('440183','440184','440113','440114','440107')";
//            }
//            if (ddlArea.SelectedItem.Text == "省内")
//            {
//                condition += " and it.ReceiveProvince='440000' and it.ReceiveCity!='440100'";
//            }
//            if (ddlArea.SelectedItem.Text == "国内")
//            {
//                condition += " and it.ReceiveProvince not in('440000','660000','670000','680000','990000')";
//            }
//            if (ddlArea.SelectedItem.Text == "国际")
//            {
//                condition += " and it.ReceiveProvince in ('660000','670000','680000','990000')";
//            }

//            return condition;
//        }

//        protected void FeedbackClick(object sender, EventArgs e)
//        {
//            string id = null;
//            HtmlInputCheckBox cb = null;
//            foreach (GridViewRow gr in gvList.Rows)
//            {
//                cb = (HtmlInputCheckBox)gr.Cells[0].FindControl("chkItem");
//                id = cb.Attributes["value"].Split(',')[0];
//                DropDownList dt;
//                if (cb.Checked)
//                {
//                    ViewState[id] = id;
//                }
//                else
//                {
//                    if (ViewState[id] != null)
//                    {
//                        ViewState.Remove(id);
//                    }
//                }
//            }
//            StringBuilder idBuilder = new StringBuilder();
//            foreach (string orderId in ViewState.Keys)
//            {
//                idBuilder.Append(orderId).Append("~");
//            }

//            if (idBuilder.Length > 0)
//            {
//                ClientHelper.Instance.RenderScript(Page, "", String.Format("feedbackOrder('{0}')", idBuilder.ToString()));
//            }
//        }
    }
}